#include "hdr_rgbe.h"
#include <sstream>
#include <stdio.h>
#include "common/math/col3.h"
#include <math.h>
using namespace std;


namespace gemren
{
	typedef unsigned char uchar;
	typedef embree::Col3f pixel;
	enum { R=0, G=1, B=2, E=3 };
	inline uchar float_to_byte(const float f)
	{
		int ret = int(0.5f+255*f);
		if(ret<0) ret = 0;
		else if(ret>255) ret = 255;
		return ret;
	}
	void col_to_rgbe(const pixel& col, uchar* rgbe)
	{
		float max = embree::reduce_max(col);
		int e;
		float m = frexp(max, &e);
		float norm = max / m; //1.00 e <e>
		
		rgbe[R] = float_to_byte(col.r/norm);
		rgbe[G] = float_to_byte(col.g/norm);
		rgbe[B] = float_to_byte(col.b/norm);

		e += 128;
		if(e < 0) e = 0;
		else if(e>255) e = 255;
		rgbe[E] = e;
	}
	bool store_hdr(const char* filename, const pixel* img, const int width, const int height)
	{
		FILE* file = fopen(filename, "wb");
		/*if(!ferror(file)) 
		{
			fclose(file);
			return false;
		}*/
		char lf = 10;
		stringstream ss;
		
		ss<<"#?RGBE\nFORMAT=32-bit_rle_rgbe\n\n";
		ss<<"-Y "<<height<<" +X "<<width<<endl;
		fwrite(ss.str().c_str(), 1, ss.str().size(), file);
		
		unsigned char rgbe[4];
		for(int i = 0; i < width*height; ++i)
		{
			col_to_rgbe(*img, rgbe);
			fwrite(rgbe, sizeof(unsigned char), 4, file);
			++img;
		}
		fclose(file);
		return true;
	}
}